package org.fast.project.app.config;

import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceUnit;

import org.fast.project.dao.function.IgnoreNullValueUpdateEventListener;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.context.annotation.Configuration;

/**
 * Hibernate 监听器配置器
 *
 * @author D·jun
 * @date 2024/10/24
 */
@Configuration
public class HibernateListenerConfigurer {
    @PersistenceUnit
    private EntityManagerFactory emf;

    @PostConstruct
    protected void init() {
        SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
        EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
        //先清除后加入 否则会造成两个重复监听器
        if (registry != null) {
            registry.getEventListenerGroup(EventType.MERGE).clearListeners();
            registry.getEventListenerGroup(EventType.MERGE).prependListener(IgnoreNullValueUpdateEventListener.INSTANCE);
        }
    }
}